package com.foreveross.bsl.mam.device.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.common.utils.mapper.BeanMapper;
import com.foreveross.bsl.common.utils.web.QueryFilter;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.common.utils.web.model.PageMustache;
import com.foreveross.bsl.common.utils.web.model.QueryModelHelper;
import com.foreveross.bsl.common.utils.web.model.SelectBoxModel;
import com.foreveross.bsl.common.utils.web.model.SortInfoModel;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.device.application.DeviceApplication;
import com.foreveross.bsl.mam.device.application.DeviceSceneApplication;
import com.foreveross.bsl.mam.device.application.vo.DeviceSceneVO;
import com.foreveross.bsl.push.application.CheckinMgmtService;
import com.foreveross.bsl.push.application.PushService;
import com.foreveross.bsl.push.application.vo.DeviceCheckinVo;
import com.foreveross.bsl.push.application.vo.MdmMessage;
import com.foreveross.bsl.push.application.vo.MessageParams;
import com.foreveross.bsl.push.application.vo.MessageVo;
import com.foreveross.bsl.push.application.vo.ReceiverTypeEnumVo;
import com.foreveross.bsl.system.application.ApplicationRegisterApplication;
import com.foreveross.bsl.web.BaseController;
import com.google.common.collect.Lists;


/**
 * 设备场景操作类
 * @author tanzhixiong
 * @2013-6-22 @下午3:01:42
 */
@Controller
@RequestMapping("/mam/device")
public class DeviceController extends BaseController{
	@Inject
	private PushService pushService;
	
	@Inject
	private DeviceApplication deviceApplication;
	
	@Inject
	private DeviceSceneApplication deviceScenceApplication;
	
	@Inject
	private CheckinMgmtService deviceCheckinService;
	
	@Inject
	private ApplicationRegisterApplication appRegClient;
	
	@Inject
	private AppMainApplication appService;
	
	
	@RequestMapping("/showdevice")
	public String showDevice(Model model,@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = "10") int pageSize,
			HttpServletRequest request) {
		String queryUrl="/mam/device/showdevice";
		QueryModelHelper queryHelper=new QueryModelHelper(queryUrl, makeQueryFields(), makeSortInfo());
		QuerySpecs querySpecs=queryHelper.populateQueryModel(model, request);
		QueryFilter qfAppId=querySpecs.getFilter("appId");
		String appId=null;
		if(qfAppId!=null){
			appId=qfAppId.getValue().toString();
			if(StringUtils.isNotBlank(appId)){
				String appKey=this.appRegClient.getAppKeyByAppId(appId);
				querySpecs.replaceFilter(qfAppId, QueryFilter.eq("appId", appKey));
			}
		}
		
		Page<DeviceCheckinVo> page=deviceCheckinService.findPageBy(pageNumber, pageSize, querySpecs);
		List<BslDeviceInfoVo> list = this.convertToBslDeviceInfos(page.getContent());
		List<DeviceSceneVO> deviceScenevo = deviceScenceApplication.findAll();
		model.addAttribute("list", list);
		model.addAttribute("deviceScenceList", deviceScenevo);
		model.addAttribute("page", new PageMustache(page, 10));
		model.addAttribute("apps", this.makeAppSelectBoxModel(appId).getOptions());
		return "device/device-list";	
	}
	
	private final SelectBoxModel makeAppSelectBoxModel(String appId){
		List<AppMainVo> apps=this.appService.findAll();
		SelectBoxModel sbm=new SelectBoxModel();
		sbm.addOption("", "所有应用", true);
		for(AppMainVo app : apps){
			sbm.addOption(app.getId(), app.getApp_name());
		}
		if(StringUtils.isNotBlank(appId)){
			sbm.setOptionSelected(appId);
		}
		return sbm;
	}
	
	private List<BslDeviceInfoVo> convertToBslDeviceInfos(List<DeviceCheckinVo> devices){
		//TODO 可将结果加入缓存
		List<BslDeviceInfoVo> list=Lists.newArrayList();
		for(DeviceCheckinVo dc : devices){
			BslDeviceInfoVo bslDi=BeanMapper.map(dc, BslDeviceInfoVo.class);
			bslDi.setBslAppId(this.appRegClient.getAppIdByAppKey(dc.getAppId()));
			bslDi.setBslAppName(bslDi.getBslAppId());
			try{
				AppMainVo app=appService.getEntity(bslDi.getBslAppId());
				if(app!=null)
					bslDi.setBslAppName(app.getApp_name());
			} catch (Exception e){
			}
			list.add(bslDi);
		}
		return list;
	}
	
	private final SelectBoxModel makeQueryFields(){
		SelectBoxModel sbm=new SelectBoxModel();
		sbm.addOption("LIKE_device_name", "设备名", true);
		sbm.addOption("EQ_device_id", "设备ID");
		sbm.addOption("LIKE_os_name", "设备系统");
		sbm.addOption("LIKE_alias", "用户名");
		return sbm;
	}
	
	private final SortInfoModel makeSortInfo(){
		SortInfoModel sim=new SortInfoModel();
		sim.setSortEntry("checkin_time", "签到时间", false);
		sim.setSortEntry("device_name", "设备名", true);
		sim.setSortEntry("alias", "用户名", true);
		return sim;
	}
	
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/sendmdm")
	public String sendmdm(@RequestParam String deviceId,
			@RequestParam String code,@RequestParam String name, @RequestParam String appId) {
		MdmMessage message = new MdmMessage();
		message.setDeviceId(deviceId);
		message.setTitle(name);
		message.setMdm(code);
		MessageParams msgp=new MessageParams();
		msgp.setReceiverType(ReceiverTypeEnumVo.DEVICE_ID);
		msgp.setReceiverValue(deviceId);
		msgp.setAppId(appId);
		msgp.setMessage(message);
		this.pushService.submitMessage(msgp);
		return "result";
	}
	
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = "/sendmessage")
	public String sendMessage(@RequestParam String deviceId,
			@RequestParam String pushMessageContent, @RequestParam String appId) {
		MessageVo message = new MessageVo();
		message.setTitle(pushMessageContent);
		MessageParams msgp=new MessageParams();
		msgp.setReceiverType(ReceiverTypeEnumVo.DEVICE_ID);
		msgp.setReceiverValue(deviceId);
		msgp.setAppId(appId);
		msgp.setMessage(message);
		this.pushService.submitMessage(msgp);
		return "result";
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(String[] ids) {
		
		String[] idss ={"",""};
		Map<String, Object> result = new HashMap<String, Object>();
		if(ids != null){
			for (int i = 0; i < idss.length; i++) {
				deviceApplication.deleteEntity(idss[i]);
			}
		}
		result.put("result", "success");
		return result;
	}

	@Override
	protected String getModuleMenuName() {
		return "设备管理";
	}
	

}
